/**
 * @Project TMHSCFX
 * @Author Tran Manh Hung
 * @Email: hungtmit@gmail.com | tmh@xwebgate.com
 * @Copyright © 2011 TMH. All rights reserved
 * @Createdate Feb 28, 2011
 * @Createtime 11:31:43 AM
 */

package com.goToAndLearn.bmpDecode
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	import flash.utils.Endian;

	public class BMPDecode extends Sprite
	{
		private var fr:FileReference;

		public function BMPDecode()
		{
			super();

			addEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
		}

		private function addToStageHandler(event:Event):void
		{
			stage.addEventListener(MouseEvent.CLICK, onClick);
		}

		private function onClick(event:MouseEvent):void
		{
			fr = new FileReference();
			fr.addEventListener(Event.SELECT, onSelect);
			fr.addEventListener(Event.COMPLETE, onComplete);
			fr.browse();
		}

		private function onSelect(event:Event):void
		{
			trace("on select");

			fr.load();
		}

		private function onComplete(event:Event):void
		{
			var ba:ByteArray = fr.data;
			ba.endian = Endian.LITTLE_ENDIAN;
			ba.position = 10;

			var pixelOffset:uint = ba.readUnsignedInt();

			ba.position += 4;

			var width:int = ba.readInt();
			var height:int = ba.readInt();

			ba.position = pixelOffset;

			var padding:uint = (width * 3) % 4;

			var bmd:BitmapData = new BitmapData(width, height, false);

			for (var y:int = height - 1; y >= 0; y--)
			{
				for (var x:int = 0; x < width; x++)
				{
					bmd.setPixel(x, y, ba.readUnsignedByte() | ba.readUnsignedByte() << 8 | ba.readUnsignedByte() << 16);
				}

				ba.position += padding;
			}

			addChild(new Bitmap(bmd));
		}
	}
}